package com.dp.mallchat.common.websocket;

import cn.hutool.core.net.url.UrlBuilder;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.FullHttpRequest;
import org.apache.commons.lang3.StringUtils;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.Objects;
import java.util.Optional;

/**
 * @Author: dupeng
 * @CreateTime: 2024-05-31  16:46
 * @Description: TODO
 */
public class MyHeaderCollectHandler extends ChannelInboundHandlerAdapter {

    public static final String X_REAL_IP = "X-Real-IP";

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof FullHttpRequest) {
            FullHttpRequest httpRequest = (FullHttpRequest) msg;
            UrlBuilder urlBuilder = UrlBuilder.ofHttp(httpRequest.uri());

            //获取token
            Optional<String> token = Optional.of(urlBuilder.getQuery())
                    .map(k -> k.get("token"))
                    .map(CharSequence::toString);
            token.ifPresent(s -> NettyUtil.setAttr(ctx.channel(), NettyUtil.TOKEN, s));
            httpRequest.setUri(urlBuilder.getPath().toString());

            //获取用户ip
            String ip = httpRequest.headers().get(X_REAL_IP);
            if (StringUtils.isBlank(ip)) {
                //未经过nginx，获取远端ip
                InetSocketAddress socketAddress = (InetSocketAddress) ctx.channel().remoteAddress();
                ip = socketAddress.getAddress().getHostAddress();
            }
            NettyUtil.setAttr(ctx.channel(), NettyUtil.IP, ip);
            ctx.pipeline().remove(this);    //将自身环节移除，MyHeaderConllectHandler
        }
        ctx.fireChannelRead(msg);
    }

}
